package logging

import (
	"fmt"
	"gin-blog/utils/helper"
	"gin-blog/utils/setting"
	"os"
	"time"
)

// 获取日志文件路径
func getLogFilePath() string {
	return fmt.Sprintf("%s%s", setting.AppSetting.RuntimeRootPath, setting.AppSetting.LogSavePath)
}

// 获取日志文件名称
func getLogFileName() string {
	//prefixPath := setting.AppSetting.LogSavePath
	//suffixPath := fmt.Sprintf("%s%s.%s", LogSaveName, time.Now().Format(setting.AppSetting.TimeFormat), setting.AppSetting.LogFileExt)
	suffixPath := fmt.Sprintf("%s.%s", time.Now().Format(setting.AppSetting.TimeFormat), setting.AppSetting.LogFileExt)

	return fmt.Sprintf("%s", suffixPath)
}

// 打开文件
func openLogFile(filename, filepath string) (*os.File, error) {
	dir, err := os.Getwd()

	if err != nil {
		return nil, fmt.Errorf("os.Getwd err: %v", err)
	}

	src := dir + "/" + filepath
	perm := helper.CheckPermission(src)

	if perm == true {
		return nil, fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}

	err = helper.IsNotExistMKDir(src)

	if err != nil {
		return nil, fmt.Errorf("file.IsNotExistMkDir src: %s, err: %v", src, err)
	}

	f, err := helper.Open(src + filename, os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0644)

	if err != nil {
		return nil, fmt.Errorf("Fail to OpenFile:%v", err)
	}

	return f, nil
}